'use strict';

const RouterService = require('../base');
const {CommonDeletedEnum} = require("../../utils/enum");

class SupplierService extends RouterService {
  static get modelName() {
    return 'Business.Supplier';
  }

  // 供应商登录
  async login(payload) {
    const { username, password } = payload;

    if (!username || !password) {
      return null;
    }

    // 查找供应商
    const supplier = await this.model.findOne({
      where: {
        username,
        password, // 明文比较
        deleted: 0
      }
    });

    if (!supplier) {
      throw new Error('账号密码不正确');
    }
    if (supplier.status === 0) {
      throw new Error('账号已被禁用,请联系管理员');
    }
    // 检查是否入围当月比价
    const currentMonth = this.getCurrentMonth();
    const isQualified = await this.checkSupplierQualification(supplier.id, currentMonth);

    if (!isQualified) {
      throw new Error('未入围当月比价');
    }

    return supplier;
  }

  // 检查供应商是否入围当月比价
  async checkSupplierQualification(supplierId, month) {
    const { ctx } = this;
    const MonthlyBidding = ctx.model.Business.MonthlyBidding;

    // 查找当月的比价记录，且该供应商被选中
    const bidding = await MonthlyBidding.findOne({
      where: {
        month,
        selected_supplier_id: supplierId,
        status: 3, // 已确定供应商
        deleted: 0
      }
    });

    return !!bidding;
  }

  // 获取当前月份 YYYY-MM 格式
  getCurrentMonth() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    return `${year}-${month}`;
  }

  async findById(id) {
    const res = await this.model.findOne({
      where: {
        id,
      },
    });
    if (!res) {
      throw new Error('该账号不存在');
    }
    if (res.status === 0) {
      throw new Error('账号已被禁用');
    }
    // 检查是否入围当月比价
    const currentMonth = this.getCurrentMonth();
    const isQualified = await this.checkSupplierQualification(res.id, currentMonth);

    if (!isQualified) {
      throw new Error('未入围当月比价');
    }

    return res
  }
}

module.exports = SupplierService;
